from DataSet_new2 import DataSet
# import pandas as pd
from 选股_对象 import *
from 回测_面向对象 import *
from DataSet_new2 import *
from Functions import *
from Factor_Alpha101_code import *
# 修改为本地存储代码数据、指数数据、生成hdf文件的地址
data_dirs = r'D:\课程资料\python\大作业\xbx_stock_2019_完整代码\data\basic-trading-data\python股票数据\Stock_data.nosyncy2'
index_dir = r'D:\课程资料\python\大作业\xbx_stock_2019_完整代码\program\量化回测系统\量化回测系统/sz000001.csv'
hdf_dir = r'D:\hdf'



# 从一堆数据中整理数据、生成选股因子、转化数据周期实例
mydataset = DataSet(data_dirs, index_dir, hdf_dir)

# 读入指数数据，生成mydataset.df_index属性
mydataset.import_index_data()


# 设置并生成因子值
alpha_factor=['alpha001', 'alpha002', 'alpha003', 'alpha004', 'alpha005', 'alpha006']
mydataset.generate_alpha(alpha_factor)


# 获取股票数据，并进行周期转换，存储到mydataset.all_stock_data属性
mydataset.get_stock_code_list_in_dir('w')

# 排序并重设索引
mydataset.sort_reindex_store(['日期', '代码'])

# 生成hdf文件并存储到hdf_dir
mydataset.all_stock_data.to_hdf(hdf_dir + r'/all_stock_data_d_py3_w8'+r'.h5', 'df', format='fixed', mode='w')

# 读取生成的hdf测试文件
# store = pd.read_hdf(hdf_dir + '/all_stock_data_d_py3_w8.h5', 'df')
# print(store)


# 选股
file_path = hdf_dir + '/all_stock_data_d_py3_w8.h5'
key = 'df'

Data = ImportData(file_path, key)  # 获取数据集
Data.reset_select_stock_num(3)  # 设置仓位数量
factor_list = ['alpha001', 'alpha002']  # 设置要选择的选股因子
# Data.select_multistock_normal(factor_list)
Data.get_ic_and_ir(factor_list)  # 获取因子ic和ir值
multistock_type = 'ic'  # 设置IC、IR选股类型
Data.select_multistock_ic_ir(factor_list, multistock_type)  # 选股
df = Data.df
df.to_hdf(r'D:\hdf\adjusted_data_all_3.h5', 'df', format='fixed', mode='w')
# print(Data.df)
# exit()


# 回测

file_path = r'D:\hdf\adjusted_data_all_3.h5'
index_path = index_dir
BackTest = BackTest(file_path, index_path)  # 获取策略选股后的数据
BackTest.cal_return()  # 返回收益率
BackTest.cal_sharpe()  # 返回夏普比率
BackTest.maxdrawdown()  # 返回最大回撤
BackTest.drawplot()  # 画出资金曲线

